package cn.hs.controller;/**
 * @author Jovan Hou 2024/10/24
 **/

import cn.hs.entity.Charge;
import cn.hs.entity.Chargetype;
import cn.hs.service.ChargeService;
import cn.hs.service.ChargeTypeService;
import cn.hs.util.Result;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * @ClassName ChargeTypeController
 * @Description TODO
 * @Author CnYuu
 * @Date 2024年10月24日 11:19
 * @Version 1.0
 */
@RestController
@RequestMapping("/chargetype")
public class ChargeTypeController
{
    @Autowired
    private ChargeTypeService service;

    @GetMapping("/selectAll")
    public Result selectAll(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
           @Param("id")
           Integer id,
            @Param("name")
            String name
    ){
        Chargetype charge = new Chargetype(id,name);
        PageInfo fms = service.findAll(pageNum, pageSize, charge);
        // 用户不存在
        return Result.success(fms);
    }

    @PostMapping("/insert")
    public Result insert(
            @RequestBody
            Chargetype charge
    ){
        int insert = service.insert(charge);
        return Result.success(insert);
    }

    @GetMapping("/delete")
    public Result delete(
            @Param("id") Integer id
    ) {
        try {
            int i = service.deleteById(id);
            if (i > 0) {
                return Result.success(i);
            } else {
                return Result.error("删除失败，数据不存在");
            }
        } catch (DataIntegrityViolationException e) {
            // 捕获外键约束异常
            return Result.error("无法删除，该类型下存在关联文章");
        } catch (Exception e) {
            // 处理其他可能的异常
            return Result.error("系统异常，请稍后重试");
        }

    }




    @PutMapping("/update")
    public Result update(
            @RequestBody Chargetype charge
    ){
        int update = service.update(charge);
        return Result.success(update);
    }

    @GetMapping("/selectByconsultid")
    public Result selectByconsultid(Long consultid){
        List<Chargetype> chargetypes = service.selectByconsultid(consultid);
        if (chargetypes.size() > 0) {
            return Result.success(chargetypes);
        }else {
            return Result.success(null);
        }
    }
}
